package com.katesoft.scale4j.persistent.tools;

import com.katesoft.scale4j.log.Logger;
import com.katesoft.scale4j.log.LogFactory;
import com.katesoft.scale4j.persistent.model.unified.BO;
import org.hibernate.HibernateException;
import org.hibernate.envers.DefaultRevisionEntity;
import org.hibernate.event.SaveOrUpdateEvent;
import org.hibernate.event.SaveOrUpdateEventListener;

import java.util.concurrent.atomic.AtomicLong;

/**
 * This is very simple in-memory unique id generator.
 * <p/>
 * this generator can't be used in clustered env, more over this class start counting from current mili seconds,
 * so you should not change system time
 * (or at least do not decrease)
 *
 * @author kate2007
 */
public class NotClusteredInMemoryIdentifierGeneratorListener implements SaveOrUpdateEventListener
{
    private AtomicLong atomicLong = new AtomicLong(System.currentTimeMillis());
    private Logger logger = LogFactory.getLogger(getClass());

    @Override
    public void onSaveOrUpdate(SaveOrUpdateEvent event) throws HibernateException
    {
        if (event.getObject() instanceof BO) {
            BO entity = (BO) event.getObject();
            if (entity.getUniqueIdentifier() == null) {
                long l = atomicLong.getAndIncrement();
                logger.debug("generated new unique_identifier %s for entity %s", l, event.getObject());
                entity.setUniqueIdentifier(l);
            }
        }
        else if (event.getObject() instanceof DefaultRevisionEntity) {
            DefaultRevisionEntity entity = (DefaultRevisionEntity) event.getObject();
            if (entity.getId() == 0) {
                long l = atomicLong.getAndIncrement();
                logger.debug("generated new unique_identifier %s for entity %s", (int) l, event.getObject());
                entity.setId((int) l);
            }
        }
    }
}
